<template>
  <div>
    <!--    查询框-->
    <a-card class="form">
      <student-form @getData="getData" @again="again"></student-form>
    </a-card>

    <!-- table -->
    <a-card class="form">
      <a-button type="primary" @click="newMember">增加</a-button>
      <a-table
          :columns="columns"
          :dataSource="data"
          :pagination="pagination"
          v-model:total="data.length"
          @change="onChange"
          @showSizeChange="onShowSizeChanger"
      >
        <template #operation="{ record }">

          <span>
            <a @click="toggle(record.key)">编辑</a>
            <a-divider type="vertical"/>
            <a-popconfirm title="是否确定删除？" @confirm="remove(record.key)" okText="确定" cancelText="取消">
              <a>删除</a>
            </a-popconfirm>
            <a-divider type="vertical"/>
                        <a class="ant-dropdown-link">
                          更多操作
                            <down-outlined/>
                        </a>
          </span>
        </template>
      </a-table>


    </a-card>
    <!--    新增按钮弹出窗-->
    <a-modal v-model:visible="isShowAdd"
             title="新增学生表信息"
             width="50%"
             ok-text="新增"
             cancel-text="取消"
             @ok="addStudent"
             @cancel="cancelStudent"

    >
      <a-form
          ref="studentFormSon"
          :model="addFormItem"
          prop="a"
          :labelCol="formItemLayout.labelCol"
          :wrapperCol="formItemLayout.wrapperCol"
          :rules="rules"
          @submit="handleSubmit"
      >
        <a-row>
          <a-col :span="10">
            <a-form-item label="姓名" name="name">
              <a-input
                  placeholder="请输入姓名"
                  v-model:value="addFormItem.name"
              />
            </a-form-item>
          </a-col>

          <a-col :span="10">
            <a-form-item label="学号" name="id">
              <a-input
                  placeholder="请输入学号"
                  v-model:value="addFormItem.id"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row class="changeRow">
          <a-col :span="10">
            <a-form-item label="班级" name="classNumber">
              <a-input
                  placeholder="请输入班级"
                  v-model:value="addFormItem.classNumber"
              />
            </a-form-item>
          </a-col>

          <a-col :span="10">
            <a-form-item name="sex" label="性别">
              <a-select placeholder="请选择性别" v-model:value="addFormItem.sex">
                <a-select-option value="男">男</a-select-option>
                <a-select-option value="女">女</a-select-option>

              </a-select>
            </a-form-item>
          </a-col>

        </a-row>
      </a-form>
    </a-modal>
    <!--    编辑按钮弹出窗-->
    <a-modal v-model:visible="isShowChange"
             title="编辑学生表信息"
             width="50%"
             ok-text="保存"
             cancel-text="取消"
             @ok="changeStudent(changeKey)"
             @cancel="cancelChangeStudent(changeKey)"

    >
      <a-form
          ref="studentFormSonB"
          :model="changeFormItem"
          :labelCol="formItemLayout.labelCol"
          :wrapperCol="formItemLayout.wrapperCol"
          :rules="rules"
          @submit="handleSubmit"
      >
        <a-row>
          <a-col :span="10">
            <a-form-item label="姓名" name="name">
              <a-input
                  placeholder="请输入姓名"
                  v-model:value="changeFormItem.name"
              />
            </a-form-item>
          </a-col>

          <a-col :span="10">
            <a-form-item label="学号" name="id">
              <a-input
                  placeholder="请输入学号"
                  v-model:value="changeFormItem.id"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row class="changeRow">
          <a-col :span="10">
            <a-form-item label="班级" name="classNumber">
              <a-input
                  placeholder="请输入班级"
                  v-model:value="changeFormItem.classNumber"
              />
            </a-form-item>
          </a-col>

          <a-col :span="10">
            <a-form-item name="sex" label="性别">
              <a-select placeholder="请选择性别" v-model:value="changeFormItem.sex">
                <a-select-option value="男">男</a-select-option>
                <a-select-option value="女">女</a-select-option>

              </a-select>
            </a-form-item>
          </a-col>

        </a-row>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
  import {
    Form,
    Card,
    Button,
    Input,
    DatePicker,
    Select,
    TimePicker,
    Popover,
    Table,
    Popconfirm,
    Divider,
    message,
    Modal
  } from 'ant-design-vue';
  import {DownOutlined} from '@ant-design/icons-vue';
  import StudentForm from "./conponents/StudentForm";
  import "../../mock/index";
  import axios from "axios";

  const FormItem = Form.Item;
  const {Option} = Select;
  const {RangePicker} = DatePicker;
  export default {
    name: "ExampleStudent",
    components: {
      StudentForm,
      ATable: Table,
      ADivider: Divider,
      AForm: Form,
      ACard: Card,
      AButton: Button,
      APopover: Popover,
      APopconfirm: Popconfirm,
      ARangePicker: RangePicker,
      ATimePicker: TimePicker,
      AInput: Input,
      AModal: Modal,
      AFormItem: FormItem,
      ASelect: Select,
      ASelectOption: Option,
      DownOutlined

    },
    mounted() {
      //初始化data
      this.init()

    },
    data() {
      return {
        loading: false,
        memberLoading: false,
        isShowAdd: false,
        isShowChange: false,

        current: 1,// 当前页
        pageSizeOptions: ['5', '10', '20', '30', '40', '50'],
        pageSize: 10,
        pagination: {
          // 自己的分页
          showQuickJumper: true,
          showSizeChanger: true,
          pageSizeOptions: ['10', '20', '30', '40', '50'],
          current: 1,
          pageSize: 10,

          showTotal: (total, range) => `当前${range[0]}-${range[1]}  共${total}条记录 `

        },

        columns: [
          {
            title: '姓名',
            dataIndex: 'name',
            key: 'name',
            width: '20%',
            slots: {customRender: 'name'}
          },
          {
            title: '学号',
            dataIndex: 'id',
            key: 'id',
            width: '20%',
            slots: {customRender: 'id'}
          },
          {
            title: '班级',
            dataIndex: 'classNumber',
            key: 'classNumber',
            width: '20%',
            slots: {customRender: 'classNumber'}
          },
          {
            title: '性别',
            dataIndex: 'sex',
            key: 'sex',
            width: '20%',
            slots: {customRender: 'sex'}
          },
          {
            title: '操作',
            key: 'action',
            slots: {customRender: 'operation'}
          }
        ],
        data2: [],
        data: [],
        formItemLayout: {
          labelCol: {span: 6},
          wrapperCol: {span: 18}
        },
        addFormItem: {

          key: 0,
          name: '',
          id: '',
          editable: false,
          classNumber: '',
          sex: '',
          score: '0'

        },
        changeFormItem: {},
        rules: {
          name: [{required: true, message: '请输入学生名字', whitespace: true}],
          id: [{required: true, message: '请输入学生学号', whitespace: true}],
          classNumber: [{required: true, message: '请输入学生班级', whitespace: true}],
          sex: [{required: true, message: '请选择学生性别'}],
        },
        errors: [],
        changeKey: '',
        beforeChangeMessage: {},
      }
    },
    methods: {
      //获得数据
      init(){
        axios.get('/api/students/getStudents')
            .then(res => {
              this.data = res.data
              console.log(res);
            })
            .catch(err => {
              console.log(err)
            })
      },
      handleSubmit(e) {
        e.preventDefault()
        this.$refs.studentForm.validateFields().then(() => {
          this.$notification['error']({
            message: 'Received values of form:',
            description: this.form
          })
        })
      },
      //新增按钮
      newMember() {
        this.isShowAdd = true
        this.init()
      },
      // 删除按钮
      remove(key) {

        axios.post('/api/students/deleteStudent',JSON.stringify(key))
            .then(res=>{
              this.data=res.data;
            })
            .catch(err=>{
              console.log(err)
            })
      },
      //编辑按钮
      toggle(key) {
        this.init()
        console.log(this.data);
        this.isShowChange = true
        this.changeKey = key

        const target = this.data.find(item => item.key === key);
        this.changeFormItem = target
        target._originalData = {...target};
        this.beforeChangeMessage = {...target}


      },



      //增加功能
      addStudent() {

        console.log(this.data);
        //新增不能为空
        if (!this.addFormItem.name || !this.addFormItem.id || !this.addFormItem.classNumber || !this.addFormItem.sex) {
          this.$message.error('请填写完整成员信息。');
          return
        }
        const length = this.data.length;
        const newStudent = {
          key: length === 0 ? 1 : this.data[length - 1].key + 1,
          name: this.addFormItem.name,
          id: this.addFormItem.id,
          classNumber: this.addFormItem.classNumber,
          editable: false,
          isNew: true,
          sex: this.addFormItem.sex
        }
        axios.post('/api/students/addStudent',JSON.stringify(newStudent))
            .then(res=>{
              this.data=res.data;
            })
            .catch(err=>{
              console.log(err)
            })
        //清除表单，关闭表单
        this.$refs.studentFormSon.resetFields()
        this.isShowAdd = false
      },
      cancelStudent() {
        this.$refs.studentFormSon.resetFields()
        this.isShowAdd = false
      },

      /*编辑功能 ---  确定和取消*/
      changeStudent(changeKey) {

        if (!this.changeFormItem.name || !this.changeFormItem.id || !this.changeFormItem.classNumber || !this.changeFormItem.sex) {

          this.$message.error('请填写完整成员信息。');


          axios.post('/api/students/changeStudent',JSON.stringify(this.changeFormItem,changeKey))
              .then(res=>{
                this.data=res.data;
              })
              .catch(err=>{
                console.log(err)
              })

          return
        }

        this.data[changeKey - 1] = this.changeFormItem

        this.isShowChange = false

        // this.$refs.studentFormSonB.resetFields()

      },
      cancelChangeStudent(changeKey) {
        this.data[changeKey - 1] = this.beforeChangeMessage

        this.$refs.studentFormSonB.resetFields()
      },

      //分页功能配置
      onShowSizeChanger(current, pageSize) {
        this.current = current;
        this.pageSize = pageSize;
      },
      onChange(pageNumber) {
        this.pagination.current = pageNumber.current;
      },

      //简易模糊搜素，相同加3分，包含加1分
      getData(formData) {
        if (this.data.length > this.data2.length) {
          this.data2 = this.data


        } else {
          this.data = this.data2


        }
        for (let i of this.data) {
          i.score = 0
        }


        let {name, number, classNumber, sex} = formData
        name = name.trim()
        number = number.trim()
        classNumber = classNumber.trim()
        sex = sex.trim()
        let tallDataName = ['name', 'id', 'classNumber',]

        if (name === '' && number === '' && classNumber === '' ) {
          this.$message.error('请填写更多查询信息。');
          return
        } else {

          for (let index in this.data) {
            [name, number, classNumber].forEach((item, itemIndex) => {

              if (item === this.data[index][tallDataName[itemIndex]]) {
                //console.log(index + item);
                this.data[index].score += 3
              } else if (((("a" + item + "b") !== "ab") && this.data[index][tallDataName[itemIndex]].indexOf(item) != -1) || ((("a" + item + "b") !== "ab") && (item.indexOf(this.data[index][tallDataName[itemIndex]]) != -1))) {
                this.data[index].score++

              }
            })

            // console.log(this.data[index].score);

          }
          this.data = this.data.filter(s => s.score > 0)

          this.data.sort((a, b) => b.score - a.score)


        }
      },
      again(formData) {
        formData.name = ''
        formData.number = ''
        formData.classNumber = ''
        formData.sex = ''

        if (this.data2.length !== 0) {

          this.data = this.data2
        }

      }
    }
  }
</script>

<style scoped>
  .form {
    margin: 20px 30px;
  }

</style>